package common.Utils;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.UUID;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class UUIDDeserializer implements JsonDeserializer<UUID> 
{
	private HashMap<String, UUID> clientIDToServerID;
	
	public UUIDDeserializer()
	{
		clientIDToServerID = new HashMap<String, UUID>();
	}
	
	@Override
	 public UUID deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException 
	 {
		UUID retVal = null;
		String clientID = json.getAsString();
		  
		try
		{
			retVal = UUID.fromString(clientID);
		}
		catch(IllegalArgumentException ex)
		{
			if(!clientIDToServerID.containsKey(clientID))
			{
				retVal = UUID.randomUUID();
				clientIDToServerID.put(json.getAsString(), retVal);
			}
			else
				retVal = clientIDToServerID.get(clientID);
		}
		
		return retVal;
	 }

	public HashMap<String, UUID> getClientIDToServerID() {
		return clientIDToServerID;
	}
}

